import GraceRequest from '@/GraceUI5/js/request/request.js';
import apiList from "./apiList";
import utils from "@/static/utils/index.js";
import store from '@/store'
import $const from "@/static/utils/constant.js";

const ENV = 'test'; // 测试环境:test / 生产环境:prod
const VERSION = 'web1.0'; // version
const SIGN = 'abcdefghijklmnopqrstuvwxyz12345467890987654321work666laotiemianqianle'; // sign签名

let apiRequest = {}; // 定义请求对象
Object.keys(apiList).forEach((apiKey) => {
	apiRequest[apiKey] = (data, successCallback = () => {}, failCallback = () => {}, completeCallback =
		() => {}) => {
		let token = uni.getStorageSync("token"); // 获取token(storage)
		let appid = uni.getStorageSync("appid"); // 获取appid(storage)
		apiHandler(apiList[apiKey].url, token, appid, data, successCallback, failCallback,
			completeCallback);
	}
});

// 请求接口处理器
let apiHandler = (url, token, appid, data, successCallback, failCallback, completeCallback) => {
	if (utils.isNull(data.isLoading) || data.isLoading) {
		uni.showLoading({
			title: '加载中',
			mask: true,
		});
	}
	GraceRequest.post(
		url, {
			data: {
				appId: appid,
				interface: url,
				params: JSON.stringify({
					...data,
					token: token,
				}),
				timestamp: utils.getTimeStamp(),
				version: VERSION,
				sign: SIGN,
			},
			header: {
				token: token
			},
		},
		(res) => {
			if (utils.isNull(data.isLoading) || data.isLoading) {
				uni.hideLoading();
			}
			if (res.status == 'ok') {
				successCallback(res.data);
			} else {
				// 系统异常
				if (res.errorCode == 987 && res.errMessage == "系统异常") {
					uni.showToast({
						title: "页面长时间未刷新，session_key已过期，请重新登录",
						icon: "none",
						mask: true,
					})
					setTimeout(() => {
						uni.clearStorageSync();
						uni.reLaunch({
							url: '/pages/login',
						})
					}, 1500);
					return;
				}
				// 未登录
				if (res.errorCode == 987 && res.errMessage == "未登录或登录已过期") {
					uni.showToast({
						title: "登录已过期，请重新登录...",
						icon: "none",
						mask: true,
					})
					setTimeout(() => {
						utils.clearStorage();
						uni.navigateTo({
							url: '/pages/login'
						});
					}, 1500);
					return;
				}
				// 报错...
				uni.showModal({
					title: "提示",
					content: res.message,
					confirmText: "确定",
					showCancel: false,
				})
				uni.hideLoading();
				failCallback(res);
			}
		},
		(error) => {
			uni.hideLoading();
			failCallback(error)
		},
		(res) => {
			completeCallback(res);
		},
	);

}

export default apiRequest;